<template>
  <div class="fa-table-setting">
    <ElRow class="grid-setting" :gutter="8">
      <ElCol :span="12">
        <ElFormItem prop="tableOptions.rows" label="行数">
          <ElInputNumber
            v-input-number-fix
            v-model="data.tableRows"
            :precision="0"
            :min="1"
            :max="data.tableRowsMax"
            :disabled="disabled"
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem prop="tableOptions.cols" label="列数">
          <ElInputNumber
            v-input-number-fix
            v-model="data.tableCols"
            :precision="0"
            :min="1"
            :max="data.tableColsMax"
            :disabled="disabled"
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem prop="textAlign" label="表格方向">
          <div class="fa-radio-button-group" :class="{ 'is-disabled': disabled }">
            <ElTooltip
              v-for="item in positions"
              :key="item.value"
              :content="item.tips"
              placement="top"
              :disabled="!item.tips"
            >
              <div
                class="fa-radio-button"
                :class="[item.icon, { 'is-active': options.headerPosition === item.value }]"
                :value="item.value"
                @click="!disabled && changePosition(item.value)"
              />
            </ElTooltip>
          </div>
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem prop="tableOptions.rowHeight" label="行高">
          <ElInputNumber
            v-model="options.rowHeight"
            :precision="0"
            :min="config.rowHeightMin"
            :max="data.tableRowsHeightMax"
            :disabled="disabled"
          />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <TableSettingFields :data="data" :disabled="disabled" />

    <TextSetting class="fa-table-setting" :data="data" :disabled="disabled" :show-font-family="false" />

    <ElFormItem prop="required" label="填写要求">
      <div class="requirement-item">
        <ElCheckbox v-model="data.required" :disabled="disabled">
          必填

          <span v-if="data.required" @click.prevent style="cursor: default">
            ，至少填写

            <ElInputNumber
              style="margin: 0 4px"
              v-model="options.requiredCount"
              :precision="0"
              :min="1"
              :max="data.tableData.length"
              :disabled="disabled"
              :controls="false"
            />

            {{ data.isVerticalTable ? '列' : '行' }}
          </span>
        </ElCheckbox>
      </div>

      <div class="requirement-item">
        <ElCheckbox v-model="options.dynamic" :disabled="disabled || data.isVerticalTable">
          动态表格
          <ElTooltip content="可额外动态新增/删除行内容" placement="right">
            <i class="fa-widget-setting__label-tips fa-icon-info"></i>
          </ElTooltip>
        </ElCheckbox>
      </div>

      <div class="requirement-item">
        <ElCheckbox v-model="options.headerHidden" :disabled="disabled">
          隐藏表头
          <ElTooltip content="填写阶段表头不作为页面展示内容">
            <i class="fa-widget-setting__label-tips fa-icon-info"></i>
          </ElTooltip>
        </ElCheckbox>
      </div>
    </ElFormItem>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, watch } from 'vue'
import { MessageBox } from 'element-ui'
import config from '@/config'
import { Widget } from '@/models'
import { TableDefault, TableHeaderPosition, TableHeaderPositionMap, TableOptions } from '@/types'
import { inputNumberFix } from '@/utils'
import TextSetting from '../input/TextSetting.vue'
import TableSettingFields from './TableSettingFields.vue'

export default defineComponent({
  name: 'FaTableSetting',

  components: { TextSetting, TableSettingFields },

  directives: {
    inputNumberFix
  },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 是否禁用 */
    disabled: {
      type: Boolean,
      default: false
    }
  },

  setup(props) {
    /** 表格选项 */
    const options = computed(() => props.data.tableOptions)

    /**
     * 监听表格选项，如果被置空则更改为默认值
     * 用以解决 ElInputNumber 手动清空值时数据不合法
     */
    watch(
      options,
      opts => {
        Object.entries(opts).forEach(async ([key, val]) => {
          if (val === undefined) {
            await nextTick()
            ;(opts as any)[key] = TableDefault[key as keyof TableOptions]
          }
        })
      },
      { deep: true }
    )

    /** 必填选项更改时更新必填数量 */
    watch(
      () => props.data.required,
      required => (options.value.requiredCount = required ? 1 : 0)
    )

    /** 纵向表格时关闭动态表格 */
    watch(
      () => props.data.isVerticalTable,
      vertical => {
        if (vertical) {
          options.value.dynamic = false
        }
      }
    )

    /** 表格数据数量变更同步更新至少必填项 */
    watch(
      () => props.data.tableData.length,
      max => {
        const { tableOptions: options } = props.data
        if (options.requiredCount > max) {
          options.requiredCount = max
        }
      }
    )

    /** 改变表头位置 */
    async function changePosition(position: TableHeaderPosition) {
      const widget = props.data
      const { tableOptions: options } = widget
      const lastPosition = options.headerPosition

      options.headerPosition = position

      const {
        tableSize: { w, h },
        page: { w: pw, h: ph }
      } = widget

      // 未超出页面
      if (!(w > pw || h > ph)) {
        options.headerPosition = position
        return
      }

      try {
        options.headerPosition = lastPosition

        await MessageBox.confirm('改变表格方向后，超出页面部份的行/列将被清除', '操作确认')

        options.headerPosition = position

        widget.tableAutoCrop()
      } finally {
        widget.isActivated = true
      }
    }

    return {
      /** 表格配置 */
      config: config.tableOption,

      /** 表格选项 */
      options,

      /** 头部位置  */
      positions: Array.from(TableHeaderPositionMap.values()),

      /** 改变表头位置 */
      changePosition
    }
  }
})
</script>

<style lang="scss">
.fa-table-setting {
  .grid-setting {
    .el-input-number {
      width: 100%;
    }
  }

  .requirement-item {
    display: block;

    .el-input-number {
      width: 40px;

      .el-input__inner {
        padding: 0;
      }
    }

    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: $color-text-primary;
    }

    .el-checkbox__label {
      display: inline-flex;
      align-items: center;
    }
  }
}
</style>
